package com.sitc.administrator.application.activity;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.sitc.administrator.application.AppContext;
import com.sitc.administrator.application.R;
import com.sitc.administrator.application.util.StaticValue;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Map;

import static com.sitc.administrator.application.util.ToastUtil.showSortToast;


public class BaseWebViewActivity extends BaseTitleActivity {


    private ViewGroup webcontent;
    private WebView wv;
    private ProgressBar progressBar;
    private View mErrorView;
    private FrameLayout flVideoContainer;

    private String title;
    private String url;
    private String baseUrl;
    private String webcfg;
    private boolean used_titlebar;
    private boolean used_pressbar;


    public String getBaseUrl() {
        return baseUrl;
    }

    public void setBaseUrl(String baseUrl) {
        this.baseUrl = baseUrl;
    }




    private boolean loadError = false;



    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        onTheme();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_web_view);
    }


    /**
     *
     * @param activity
     * @param title
     * @param url
     */
    public static void start_WebView(Activity activity, String title, String url,String args) {
        Intent intent = new Intent(activity, BaseWebViewActivity.class);
        intent.putExtra(StaticValue.TITLE, title);
        intent.putExtra(StaticValue.URL, url);
        intent.putExtra(StaticValue.ARGS, args);
        intent.putExtra(StaticValue.WebCFG,"");
        activity.startActivity(intent);
    }

    public static void start_WebViewWithCfg(Activity activity, String title, String url,String args,String cfg) {
        Intent intent = new Intent(activity, BaseWebViewActivity.class);
        intent.putExtra(StaticValue.TITLE, title);
        intent.putExtra(StaticValue.URL, url);
        intent.putExtra(StaticValue.ARGS, args);
        intent.putExtra(StaticValue.WebCFG, cfg);
        activity.startActivity(intent);
    }

    @Override
    protected void initViews() {
        super.initViews();

        webcfg = getIntent().getStringExtra(StaticValue.WebCFG);

        if(webcfg!=null && !webcfg.equals("")){

            try {

                JSONObject jsonObject = new JSONObject(webcfg);
                String is_titlebar= jsonObject.getString("used_titlebar");
                String is_pressbar= jsonObject.getString("used_pressbar");

                if(is_titlebar!=null && is_titlebar.equals("yes")){
                    used_titlebar = true;
                }else {used_titlebar = false;};

                if(is_pressbar!=null && is_pressbar.equals("yes")){
                    used_pressbar = true;
                }else {used_pressbar = false;};


            } catch (JSONException e) {
                e.printStackTrace();

            }


        }else {

            used_titlebar = true;
            used_pressbar = true;
        };


        if(!used_titlebar){
            toolbar.setVisibility(View.GONE);
        }

        enableBackMenu();
        webcontent = (ViewGroup)findViewById(R.id.web_content);
        wv=findViewById(R.id.wv);
        progressBar  =findViewById(R.id.progressBar);
        mErrorView = findViewById(R.id.weberro);
        //mErrorView = LayoutInflater.from(this).inflate(R.layout.weberro,null,true);
        Button bt = (Button) mErrorView.findViewById(R.id.reload);
        flVideoContainer = findViewById(R.id.flVideoContainer);

        bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                webcontent.setVisibility(View.VISIBLE);
                mErrorView.setVisibility(View.GONE);
                wv.loadUrl(url);

            }
        });

        //先屏蔽重加载偶尔出现异常
        bt.setVisibility(View.GONE);


        wv.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView webview,String url){

                webview.loadUrl(url);
                return  true;
            }


            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

                webcontent.setVisibility(View.GONE);
                mErrorView.setVisibility(View.VISIBLE);
                loadError = true;

            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                if(used_pressbar){
                    progressBar.setVisibility(View.GONE);
                }

                if (loadError != true) {
                    mErrorView.setVisibility(View.GONE);
                    webcontent.setVisibility(View.VISIBLE);

                    String args = getIntent().getStringExtra(StaticValue.ARGS);
                    if(args!=null&&!StringUtils.isEmpty(args)){

                        doJS("OnWebReady",args);
                        /*API Leve >=19
                        wv.evaluateJavascript(args, new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String value) {

                            }
                        });
                        */
                    }
                }


            }
        });

        wv.setWebChromeClient(new WebChromeClient(){

            WebChromeClient.CustomViewCallback mCallback;

            @Override
            public void onProgressChanged(WebView view, int newProgress) {

                if(newProgress==100){
                    if(used_pressbar){
                        progressBar.setVisibility(View.GONE);
                    }
                }
                else{

                    if(used_pressbar){
                        progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                        progressBar.setProgress(newProgress);//设置进度值
                    }

                }

            }


            @Override
            public void onShowCustomView(View view, CustomViewCallback callback) {

                fullScreen();

                wv.setVisibility(View.GONE);
                flVideoContainer.setVisibility(View.VISIBLE);
                flVideoContainer.addView(view);
                mCallback = callback;
                super.onShowCustomView(view, callback);
            }

            @Override
            public void onHideCustomView() {

                fullScreen();

                wv.setVisibility(View.VISIBLE);
                flVideoContainer.setVisibility(View.GONE);
                flVideoContainer.removeAllViews();
                super.onHideCustomView();

            }


        });


        WebSettings webSetting = wv.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setDisplayZoomControls(false);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setDomStorageEnabled(true);


        //webSetting.setAppCacheEnabled(false);
        //webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        //webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());

        webSetting.setDatabaseEnabled(true);
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());

        webSetting.setGeolocationEnabled(true);
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());

        //webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        //webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);

        //跨域问题！
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.JELLY_BEAN){

            webSetting.setAllowUniversalAccessFromFileURLs(true);

        }
        //本地调用对象 OS
        wv.addJavascriptInterface(new JavaScriptinterface(this),"OS");

    }

    @Override
    protected void initDatas() {
        super.initDatas();
        title = getIntent().getStringExtra(StaticValue.TITLE);
        url = getIntent().getStringExtra(StaticValue.URL);
        if(title!=null&&!StringUtils.isEmpty(title)){
            setTitle(title);
        }else {
            setTitle("");
        }

        setBaseUrl(StaticValue.BASEURL);



        if (!TextUtils.isEmpty(url)) {
            Log.d("TAG",url);
            long time = System.currentTimeMillis();
            wv.loadUrl(url);
            Log.d("time-cost", "cost time: "
                    + (System.currentTimeMillis() - time));
        }
    }


    protected void doJS(String methods,String args){

        String text = String.format("javascript:%s('%s')",methods,args);
        wv.loadUrl(text);

    }


    private void fullScreen() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            //横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

            toolbar.setVisibility(View.GONE);


        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

            toolbar.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(wv !=null){
            wv.destroy();
        }

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    }


}


class JavaScriptinterface {

    private BaseWebViewActivity mActivity;

    public JavaScriptinterface(BaseWebViewActivity activity) {
        this.mActivity = activity;

    }

    /**打开一个webview
     * @param args
     */
    @JavascriptInterface
    public void openWebView(final String args) {

        new Handler().post(new Runnable() {
            @Override
            public void run() {

                //解析args e.g {title："",url:"",args:""}
                if(args!=null&&!StringUtils.isEmpty(args)){

                    try {

                        JSONObject jsonObject = new JSONObject(args);
                        String title = jsonObject.getString("title");
                        String url = mActivity.getBaseUrl()+jsonObject.getString("url");
                        String webargs = jsonObject.getString("args");
                        mActivity.startWebView(title,url,webargs);

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                }

            }
        });
    }


    /**打开一个带配置的webview
     * @param args
     */
    @JavascriptInterface
    public void openWebViewWithCfg(final String args) {

        new Handler().post(new Runnable() {
            @Override
            public void run() {

                //解析args e.g {title："",url:"",args:""}
                if(args!=null&&!StringUtils.isEmpty(args)){

                    try {

                        JSONObject jsonObject = new JSONObject(args);
                        String title = jsonObject.getString("title");
                        String url = mActivity.getBaseUrl()+jsonObject.getString("url");
                        String webargs = jsonObject.getString("args");
                        String webcfg = jsonObject.getString("webcfg");
                        mActivity.startWebViewWithCfg(title,url,webargs,webcfg);

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                }

            }
        });
    }

    /**打开一个带配置的webview
     * @param args
     */
    @JavascriptInterface
    public void openScene(final String args) {

        new Handler().post(new Runnable() {
            @Override
            public void run() {

                AppContext app = (AppContext)mActivity.getApplication();
                Map<String, String> scentMap = app.getSceneMap();
                String activityClassName = scentMap.get(args);
                if(activityClassName!=null && !activityClassName.equals("")){

                    try {
                        mActivity.startActivity(Class.forName(activityClassName));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }

                }

            }
        });
    }



    /**
     * 返回
     */
    @JavascriptInterface
    public void onBack(){
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                mActivity.finish();
            }
        });
    }

    @JavascriptInterface
    public void toast(final String text){
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                showSortToast(mActivity,text);
            }
        });
    }

    /**获取日期
     * @param args
     */
    @JavascriptInterface
    public void getDate(final String args){

        mActivity.runOnUiThread(new Runnable() {

            @Override
            public void run() {

                Date _date = null;
                //解析args e.g {date："2019-06-18"}
                if(args!=null&&!StringUtils.isEmpty(args)){

                    try {

                        JSONObject jsonObject = new JSONObject(args);
                        String date = jsonObject.getString("date");

                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
                        _date = simpleDateFormat.parse(date);

                    } catch (JSONException e) {
                        e.printStackTrace();
                        return;
                    } catch (ParseException e) {
                        e.printStackTrace();
                        return;
                    }

                }


                Calendar cal = Calendar.getInstance();
                cal.setTime(_date);

                final DatePickerDialog mDialog =new DatePickerDialog(mActivity,null,
                        cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
                //手动设置按钮
                mDialog.setButton(DialogInterface.BUTTON_POSITIVE,"完成",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog,int which){
                        //通过mDialog.getDatePicker()获得dialog上的DatePicker组件，然后可以获取日期信息
                        DatePicker datePicker = mDialog.getDatePicker();
                        String year = datePicker.getYear()+"";
                        String month = datePicker.getMonth()>10? (""+datePicker.getMonth()):("0"+datePicker.getMonth());
                        String day = datePicker.getDayOfMonth()>10? (""+datePicker.getDayOfMonth()):("0"+datePicker.getDayOfMonth());

                        String date = String.format("%s-%s-%s",year,month,day);
                        mActivity.doJS("OnDate",date);
                    }
                });

                //取消按钮，如果不需要直接不设置即可
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog,int which){

                    }
                });
                mDialog.show();

            }
        });




    }


    @JavascriptInterface
    public void setItem(final String args){

        if(args!=null&&!StringUtils.isEmpty(args)){

            try {

                JSONObject jsonObject = new JSONObject(args);
                String key = jsonObject.getString("Key");
                String Value = jsonObject.getString("Value");
                mActivity.getSp().put(key,Value);

            } catch (JSONException e) {
                e.printStackTrace();
                return;
            }

        }
    }



    @JavascriptInterface
    public String getItem(final String args){

        if(args!=null&&!StringUtils.isEmpty(args)){

           return mActivity.getSp().get(args);

        }

        return "";
    }

    @JavascriptInterface
    public void setOrientation(final String args){

        if(args!=null&&!StringUtils.isEmpty(args)){

            if(args.equals("SCREEN_ORIENTATION_PORTRAIT")){
                mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }else if(args.equals("SCREEN_ORIENTATION_REVERSE_LANDSCAPE")){

                mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
            }if(args.equals("SCREEN_ORIENTATION_REVERSE_PORTRAIT")){

                mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
            }if(args.equals("SCREEN_ORIENTATION_LANDSCAPE")){

                mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }

        }


    }






}





